import React, { Component } from 'react'
import {Navigate  } from 'react-router-dom'
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Form, Input, message } from 'antd';
import {withRouter} from '../../utils/withRouter'
import MemoryModel from '../../utils/memoryUtils';
import localStorageUtils from '../../utils/LocalStore';
import './login.less'
import { reqLogin } from '../../api/index'
import logo from '../../assets/images/logo.png'



class Login extends Component {

  onFinish = async (values) => {
    // 结构出来 
    const { username, password } = values
    const result = await reqLogin(username, password)
    console.log("@@@", result)
    if (result.status === 0) {
      message.success('登录成功')
      MemoryModel.user=result.data
      localStorageUtils.saveUser(result.data)
      this.props.router.navigate('/', { 
        replace: true,
        state: { from: 'admin' }  // 可传状态
      });
    } else {
      message.error(result.msg)
    }
  }
  render() {

    const user= MemoryModel.user
    if(user._id){
      //user_id 有值的时候, 直接跳转到首页的界面 
      return <Navigate to='/' replace ></Navigate>
    }


    return (
      <div className='login'>
        <header className='login-header'>

          <img src={logo} alt='logo'></img>
          <h1>React项目:后台管理系统</h1>

        </header>
        {/*  内容分组  */}
        <section className='login-content'>
          <h2>用户登录</h2>
          <Form
            name="login"
            initialValues={{ remember: true }}
            style={{ maxWidth: 360 }}
            onFinish={this.onFinish}
          >
            <Form.Item
              name="username"
              rules={
                // 声明式验证:直接使用别人写好的验证规则 
                [
                  { required: true, message: '请输入你的用户名' },
                  { min: 4, message: '用户名至少4位' },
                  { max: 12, message: '用户名最多12位' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名必须是英文,数字或者下划线' }
                ]
              }
            >
              <Input prefix={<UserOutlined />} placeholder="用户名" />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                { required: true, message: '请输入你的密码' },
                // ({getFieldValue})=>({
                //   validator(_,value){
                //     if(!value||getFieldValue('password')===value){
                //       return Promise.resolve()
                //     }
                //     return Promise.reject(new Error('The new Password'))
                //   }
                // }),

              ]}
            >
              <Input prefix={<LockOutlined />} type="password" placeholder="密码" />
            </Form.Item>


            <Form.Item>
              <Button block type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </section>
      </div>
    )
  }
}


export default withRouter(Login)